<?php

namespace addons\filewatcher\library;

ini_set('display_errors', 'on');

use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 文件修改监测服务
 */
class Filewatcher extends Command
{

    protected function configure()
    {
        $this->setName('filewatcher')
            ->setDescription('文件变化监测服务');
    }

    protected function execute(Input $input, Output $output)
    {
        if (!config('app_debug')) {
            $output->error("仅支持调试模式下使用");
            return;
        }
        $config = get_addon_config('filewatcher');

        $params = $config;
        $params['ignored'] = array_filter(explode("\n", str_replace(["\r\n", "\r"], "\n", str_replace("\\", "/", $params['ignored']))));
        $params['workdir'] = ROOT_PATH;

        try {
            $nodeExec = exec("which node");
            if (!$nodeExec) {
                throw new Exception("node environment not found!please install node first!");
            }
            $command = $nodeExec . " " . dirname(dirname(__FILE__)) . '/nodejs/index.js' . " " . "'" . json_encode($params) . "'";
            if ($input->getOption('verbose')) {
                $output->comment($command);
            }

            $descriptorspec = [
                0 => ["pipe", "r"],
                1 => ["pipe", "w"],
                2 => ["pipe", "w"],
            ];
            $process = proc_open($command, $descriptorspec, $pipes);
            if (is_resource($process)) {
                while ($s = fgets($pipes[1])) {
                    print $s;
                }

                proc_close($process);
            }

            //echo shell_exec($command);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

    }

}
